package com.example.haoqisystem.service;

import com.example.haoqisystem.request.EmailRequest;
import com.example.haoqisystem.response.BaseResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.activation.DataHandler;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.activation.DataSource;
import javax.mail.util.ByteArrayDataSource;
import java.nio.file.Files;
import java.nio.file.Path;

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class EmailService {
    private final JavaMailSender javaMailSender;

    // 发送邮件
    public BaseResponse<String> sendEmail(EmailRequest request) {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

            helper.setTo(request.getTo());
            helper.setSubject(request.getSubject());

            MimeMultipart multipart = new MimeMultipart();

            // 纯文本正文
            MimeBodyPart textPart = new MimeBodyPart();
            textPart.setText(request.getBody());
            multipart.addBodyPart(textPart);

            String data = "未添加附件";
            // 添加附件
            if (request.getAttachmentPath() != null && !request.getAttachmentPath().equals("")) {
                data = addAttachment(multipart, request.getAttachmentPath());
            }
            mimeMessage.setContent(multipart);
            helper.setFrom("2157834851@qq.com");
            javaMailSender.send(mimeMessage);
            return new BaseResponse<>("邮件成功发送至" + request.getTo(), true, data);
        } catch (MailException | MessagingException e) {
            log.error("向" + request.getTo() + "发送邮件时出错", e);
            return new BaseResponse<>("向" + request.getTo() + "发送邮件时出错", false, null);
        }
    }

    private String addAttachment(MimeMultipart multipart, Path attachmentPath) {
        try {
            MimeBodyPart attachmentBodyPart = new MimeBodyPart();
            byte[] attachments = Files.readAllBytes(attachmentPath);
            DataSource dataSource = new ByteArrayDataSource(attachments, "application/octet-stream");
            attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
            attachmentBodyPart.setFileName(attachmentPath.getFileName().toString());
            multipart.addBodyPart(attachmentBodyPart);
            return "添加附件成功";
        } catch (Exception e) {
            log.error("附件添加失败", e);
            return "附件添加失败" + e.getMessage();
        }
    }
}












